/*
 * Academic License - for use in teaching, academic research, and meeting
 * course requirements at degree granting institutions only.  Not for
 * government, commercial, or other organizational use.
 *
 * findpeaks.c
 *
 * Code generation for function 'findpeaks'
 *
 */

/* Include files */
#include "findpeaks.h"
#include "eml_setop.h"
#include "rt_nonfinite.h"
#include "rt_nonfinite.h"
#include <math.h>
#include <string.h>

/* Function Definitions */
int findpeaks(const double Yin_data[], int Yin_size,
              const double varargin_1_data[], double Ypk_data[],
              double Xpk_data[], int Xpk_size[2])
{
  double ykfirst;
  int c_data[2050];
  int fPk_data[1025];
  int iFinite_data[1025];
  int iInfinite_data[1025];
  int iPk_data[1025];
  int Ypk_size;
  int iFinite_size;
  int k;
  int kfirst;
  int n;
  int nInf;
  int nPk;
  short idx_data[2050];
  short y_data[2050];
  char dir;
  boolean_T isinfykfirst;
  nPk = 0;
  nInf = 0;
  dir = 'n';
  kfirst = 0;
  ykfirst = rtInf;
  isinfykfirst = true;
  for (k = 1; k <= Yin_size; k++) {
    double yk;
    boolean_T isinfyk;
    yk = Yin_data[k - 1];
    if (rtIsNaN(yk)) {
      yk = rtInf;
      isinfyk = true;
    } else if (rtIsInf(yk) && (yk > 0.0)) {
      isinfyk = true;
      nInf++;
      iInfinite_data[nInf - 1] = k;
    } else {
      isinfyk = false;
    }
    if (yk != ykfirst) {
      char previousdir;
      previousdir = dir;
      if (isinfyk || isinfykfirst) {
        dir = 'n';
      } else if (yk < ykfirst) {
        dir = 'd';
        if (previousdir == 'i') {
          nPk++;
          iFinite_data[nPk - 1] = kfirst;
        }
      } else {
        dir = 'i';
      }
      ykfirst = yk;
      kfirst = k;
      isinfykfirst = isinfyk;
    }
  }
  if (nPk < 1) {
    iFinite_size = 0;
  } else {
    iFinite_size = nPk;
  }
  nPk = 0;
  for (k = 0; k < iFinite_size; k++) {
    n = iFinite_data[k];
    ykfirst = Yin_data[n - 1];
    if ((ykfirst > rtMinusInf) &&
        (ykfirst - fmax(Yin_data[n - 2], Yin_data[n]) >= 0.0)) {
      nPk++;
      iPk_data[nPk - 1] = n;
    }
  }
  if (nPk < 1) {
    nPk = 0;
  }
  if (nInf < 1) {
    nInf = 0;
  }
  kfirst = do_vectors(iPk_data, nPk, iInfinite_data, nInf, c_data, fPk_data, &n,
                      iFinite_data, &iFinite_size);
  if (kfirst < 1) {
    n = 0;
  } else {
    n = kfirst;
  }
  if (n > 0) {
    y_data[0] = 1;
    kfirst = 1;
    for (k = 2; k <= n; k++) {
      kfirst++;
      y_data[k - 1] = (short)kfirst;
    }
  }
  if (n - 1 >= 0) {
    memcpy(&idx_data[0], &y_data[0], (unsigned int)n * sizeof(short));
  }
  if (n > Yin_size) {
    n = Yin_size;
  }
  if (n < 1) {
    Ypk_size = 0;
  } else {
    Ypk_size = n;
  }
  Xpk_size[0] = 1;
  Xpk_size[1] = Ypk_size;
  for (n = 0; n < Ypk_size; n++) {
    kfirst = c_data[idx_data[n] - 1];
    Ypk_data[n] = Yin_data[kfirst - 1];
    Xpk_data[n] = varargin_1_data[kfirst - 1];
  }
  return Ypk_size;
}

/* End of code generation (findpeaks.c) */
